<template>
  <div>
    <el-dialog
      :title="title"
      :fullscreen=true
      :close-on-click-modal="false"
      :visible.sync="visible"
      @close="OnClose">
      <el-row :gutter="10">
        <el-col :span="15">
          <el-card shadow="never" :body-style="contentViewHeight" class="uni-map-panel">
            <PointAddList ref="pointAddList" :floorId='inputForm.floor.id' type="room"
                          url='/smis/bookshelf/jfBookshelf/list' nameKey='name' @onMapClick="onMapClick"
                          @onDataClick="onDataClick" @onLoadComplete="onLoadComplete"
                          @dbClick="doSubmit()"></PointAddList>
          </el-card>
        </el-col>
        <el-col :span="9">
          <el-card shadow="never" :body-style="contentViewHeight" class="uni-data-panel">
            <el-button type="text" style="float: right; margin-bottom: 20px;" v-if="hasPermission('smis:system')"
                       @click="doRecordSubmit()" v-noMoreClick>上传记录
            </el-button>

            <el-form :model="inputForm" ref="inputForm" v-loading="loading" :class="method==='view'?'readonly':''"
                     :disabled="method==='view'"
                     label-width="120px">
              <el-row :gutter="15">
                <el-col :span="22">
                  <el-form-item label="id" prop="id"
                                :rules="[
                       ]">
                    <el-input v-model="inputForm.id" :placeholder="!autoId ? '请填写点位id' : '无需填写' "
                              :readonly="autoId"></el-input>
                    <el-checkbox v-model="autoId" style="position: absolute; right: 5px; ">自动</el-checkbox>
                  </el-form-item>
                </el-col>
                <el-col :span="22">
                  <el-form-item label="点位名称" prop="name"
                                :rules="[
                       ]">
                    <el-input v-model="inputForm.name" placeholder="请填写名称"></el-input>
                    <el-checkbox v-model="autoUp" style="position: absolute; right: 5px; ">自增</el-checkbox>
                  </el-form-item>
                </el-col>
                <el-col :span="22">
                  <el-form-item label="点位类型" prop="pointType">
                    <el-select v-model="inputForm.pointType" placeholder="请选择点位类型" style="width: 100%;">
                      <el-option label="巡更" value="巡更"></el-option>
                      <el-option label="巡检" value="巡检"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="22">
                  <el-form-item label="x轴" prop="x"
                                :rules="[
                        {required: true, message:'x轴不能为空', trigger:'blur'}
                       ]">
                    <el-input v-model="inputForm.x" placeholder="请填写x轴"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="22">
                  <el-form-item label="y轴" prop="y"
                                :rules="[
                        {required: true, message:'y轴不能为空', trigger:'blur'}
                       ]">
                    <el-input v-model="inputForm.y" placeholder="请填写y轴"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="22">
                  <el-form-item label="z轴" prop="z"
                                :rules="[
                        {required: true, message:'z轴不能为空', trigger:'blur'}
                       ]">
                    <el-input v-model="inputForm.z" placeholder="请填写z轴"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="22" v-if="inputForm.pointType === '巡检'">
                  <el-form-item label="正常状态说明" prop="normalStatusDescription">
                    <el-input v-model="inputForm.normalStatusDescription" placeholder="请填写正常状态说明" type="textarea" :rows="2"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="22" v-if="inputForm.pointType === '巡检'">
                  <el-form-item label="正常状态图示" prop="normalStatusImages">
                    <el-upload
                      :action="`${$http.BASE_URL}/sys/file/webupload/upload?uploadPath=/smis/bookshelf/normalStatus`"
                      :headers="{token: $cookie.get('token')}"
                      list-type="picture-card"
                      :file-list="normalStatusImageList"
                      :on-preview="handlePictureCardPreview"
                      :on-remove="handleRemove"
                      :on-success="(response, file, fileList) => {
                        inputForm.normalStatusImages = fileList.map(item => (item.response && item.response.url) || item.url).join('|')
                      }">
                      <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                      <img width="100%" :src="dialogImageUrl" alt="">
                    </el-dialog>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <el-button type="primary" @click="doSubmit()" v-noMoreClick>添加(双击选中并提交)</el-button>
            <el-button type="info" style="margin-left: 50px; margin-bottom: 10px;" v-if="hasPermission('smis:system')"
                       @click="doOfflineRecord()" v-noMoreClick>离线记录
            </el-button>
            <div class="uni-notice" v-if="hasPermission('smis:system')">
              网络不好环境，可先离线记录数据，待网络通畅后上传至服务器
            </div>
            <div class="uni-addlist-delete" v-if="selectItem.id !== ''">
              <div>当前选中了{{ selectItem.name }}</div>
              <el-button type="danger" size="small" @click="doDelete()" v-noMoreClick>删除</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import SelectTree from '@/components/treeSelect/treeSelect.vue'
import PointAddList from '@/components/jfMap/pointAddList.vue'

export default {
  data () {
    return {
      title: '',
      method: '',
      autoUp: false,
      autoId: true,
      visible: false,
      loading: false,
      selectItem: {
        id: '',
        name: ''
      },
      dialogImageUrl: '',
      dialogVisible: false,
      normalStatusImageList: [],
      inputForm: {
        id: '',
        floor: {
          id: ''
        },
        name: '',
        pointType: '巡更', // 默认为巡更
        normalStatusDescription: '',
        normalStatusImages: '',
        x: '',
        y: '',
        z: ''
      }
    }
  },
  components: {
    SelectTree,
    PointAddList
  },
  watch: {
    'inputForm.pointType': function (newVal) {
      if (newVal === '巡检') {
        this.initNormalStatusImageList()
      } else {
        this.inputForm.normalStatusDescription = ''
        this.inputForm.normalStatusImages = ''
        this.normalStatusImageList = []
      }
    }
  },
  computed: {
    contentViewHeight () {
      let height = this.$store.state.common.documentClientHeight - 152
      return {height: height + 'px'}
    }
  },
  methods: {
    init (method, id, floorId) {
      this.method = method
      this.inputForm.id = id
      this.title = `批量添加`
      this.visible = true
      this.loading = false
      this.$nextTick(() => {
        // 确保新增和修改时都传入楼层信息
        this.inputForm.floor.id = floorId
        this.resetFields()
        this.$refs.pointAddList.resize()
        this.$refs.pointAddList.showFloor(floorId)

        // 如果是编辑模式，加载数据
        if (method === 'edit' && id) {
          this.loading = true
          this.$http({
            url: `/smis/bookshelf/jfBookshelf/queryById?id=${id}`,
            method: 'get'
          }).then(({data}) => {
            if (data && data.success) {
              const bookshelf = data.jfBookshelf
              this.inputForm = this.recover(this.inputForm, bookshelf)
              // 初始化图片列表和状态说明
              if (this.inputForm.pointType === '巡检') {
                this.inputForm.normalStatusDescription = bookshelf.normalStatusDescription || ''
                this.inputForm.normalStatusImages = bookshelf.normalStatusImages || ''
                this.initNormalStatusImageList()
              }
              // 确保点位在地图上正确显示，无论是巡检还是巡更
              this.$refs.pointAddList.addMarkPoint(
                this.inputForm.id,
                this.inputForm.name,
                this.inputForm.floor.id,
                this.inputForm.x,
                this.inputForm.y,
                this.inputForm.z || 0
              )
            }
            this.loading = false
          })
        }
      })
    },
    resetFields () {
      // 如果是编辑模式，不能清空id和floor信息
      if (this.method !== 'edit') {
        this.inputForm.id = ''
        // 保留楼层信息，不再清空 floor
      }

      // 名称根据自增规则处理
      this.inputForm.name = this.autoUp ? this.getAutoUpNumber(this.inputForm.name) : ''

      // 重置其他字段
      this.inputForm.pointType = '巡更' // 默认为巡更
      this.inputForm.normalStatusDescription = ''
      this.inputForm.normalStatusImages = ''
      this.normalStatusImageList = []
      this.inputForm.x = ''
      this.inputForm.y = ''
      this.inputForm.z = ''
    },
    handleRemove (file, fileList) {
      // 删除服务器上的文件
      if (file.response && file.response.url) {
        this.$http.post(`/sys/file/webupload/deleteByUrl?url=${file.response.url}`).then(({data}) => {
          this.$message.success(data.msg)
        })
      } else if (file.url) {
        this.$http.post(`/sys/file/webupload/deleteByUrl?url=${file.url}`).then(({data}) => {
          this.$message.success(data.msg)
        })
      }
      // 更新表单数据
      this.inputForm.normalStatusImages = fileList.map(item => (item.response && item.response.url) || item.url).join('|')
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    initNormalStatusImageList () {
      if (this.inputForm.normalStatusImages) {
        const imgUrls = this.inputForm.normalStatusImages.split('|')
        this.normalStatusImageList = imgUrls.map(url => {
          const fileName = url.substring(url.lastIndexOf('/') + 1)
          return {
            name: fileName,
            url: url
          }
        })
      } else {
        this.normalStatusImageList = []
      }
    },
    getAutoUpNumber (code) {
      if (!code || code === '') {
        return ''
      }
      var list = code.split('')
      var numCode = ''
      for (var i = list.length - 1; i >= 0; i--) {
        var isnum = /^\d+$/.test(list[i])
        if (isnum) {
          numCode = list[i] + numCode
        } else {
          break
        }
      }
      if (numCode === '') {
        return code
      }
      var prefix = code.substr(0, code.length - numCode.length)
      var newCode = (parseInt(numCode) + 1) + ''
      for (var len = newCode.length, i = 0; i < numCode.length - len; i++) {
        newCode = '0' + newCode
      }
      return prefix + newCode
    },
    // 处理图片移除
    handleRemoveImage (file, fileList) {
      // 删除服务器上的文件
      if (file.response && file.response.url) {
        this.$http.post(`/sys/file/webupload/deleteByUrl?url=${file.response.url}`).then(({data}) => {
          this.$message.success(data.msg)
        })
      } else if (file.url) {
        this.$http.post(`/sys/file/webupload/deleteByUrl?url=${file.url}`).then(({data}) => {
          this.$message.success(data.msg)
        })
      }
      // 更新表单数据
      this.inputForm.normalStatusImages = fileList.map(item => (item.response && item.response.url) || item.url).join('|')
    },
    // 表单提交
    doSubmit (callback) {
      this.$refs['inputForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          // 提交完整的floor对象
          const submitData = {
            ...this.inputForm
          }
          // 确保图片地址正确传递
          submitData.normalStatusImages = this.inputForm.normalStatusImages
          this.$http({
            url: `/smis/bookshelf/jfBookshelf/save`,
            method: 'post',
            data: submitData
          }).then(({data}) => {
            if (data && data.success) {
              this.$message.success(data.msg)
              this.$refs.pointAddList.refreshList()
              this.resetFields()
              callback && callback()
            }
            this.loading = false
          })
        }
      })
    },
    getRecordList () {
      var recordStr = localStorage.getItem('bookshelfRecordList')
      if (recordStr && recordStr.length > 4) {
        return JSON.parse(recordStr)
      }
      return []
    },
    // 上传保存离线记录
    doRecordSubmit () {
      var recordList = this.getRecordList()
      if (recordList.length > 0) {
        this.inputForm = recordList.pop()
        this.$nextTick(() => {
          this.doSubmit(() => {
            this.$refs.pointAddList.removeMarkPoint(this.inputForm.name)
            localStorage.setItem('bookshelfRecordList', JSON.stringify(recordList))
            this.doRecordSubmit()
          })
        })
      }
    },
    // 离线记录
    doOfflineRecord () {
      this.inputForm.filesAll = JSON.stringify(this.inputForm.file)
      this.$refs['inputForm'].validate((valid) => {
        if (valid) {
          var recordList = this.getRecordList()
          recordList.push(this.inputForm)
          localStorage.setItem('bookshelfRecordList', JSON.stringify(recordList))
          this.$message.success('已存储至缓存，当前缓存记录数：' + recordList.length + '条')
          this.$refs.pointAddList.addMarkPoint(this.inputForm.id, this.inputForm.name, this.inputForm.floor.id, this.inputForm.x, this.inputForm.y, this.inputForm.z || 0)
          this.resetFields()
        }
      })
    },
    onLoadComplete () {
      setTimeout(() => {
        var recordList = this.getRecordList()
        for (var i = 0; i < recordList.length; i++) {
          this.$refs.pointAddList.addMarkPoint(recordList[i].id, recordList[i].name, recordList[i].floor.id, recordList[i].x, recordList[i].y, recordList[i].z || 0)
        }
      }, 100)
    },
    // 初始化正常状态图片列表
    doDelete () {
      // 检查缓存是否存在，存在则删缓存的
      var recordList = this.getRecordList()
      for (var i = 0; i < recordList.length; i++) {
        if (recordList[i].name === this.selectItem.id) {
          this.$message.success('已删除对应缓存记录')
          this.$refs.pointAddList.removeMarkPoint(this.selectItem.id)
          this.selectItem = {
            id: '',
            name: ''
          }
          recordList.splice(i, 1)
          localStorage.setItem('bookshelfRecordList', JSON.stringify(recordList))
          return
        }
      }
      this.loading = true
      this.$http({
        url: '/smis/bookshelf/jfBookshelf/delete',
        method: 'delete',
        params: {'ids': this.selectItem.id}
      }).then(({data}) => {
        if (data && data.success) {
          this.$message.success(data.msg)
          this.$refs.pointAddList.refreshList()
          this.selectItem = {
            id: '',
            name: ''
          }
        }
        this.loading = false
      })
    },
    onMapClick (e) {
      this.inputForm.x = e.x
      this.inputForm.y = e.y
      this.inputForm.z = e.z
    },
    onDataClick (e) {
      this.selectItem = e
    },
    OnClose () {
      this.$emit('refreshDataList')
    },
    // 恢复表单数据
    recover (form, source) {
      if (source && typeof source === 'object') {
        Object.keys(form).forEach(key => {
          if (source[key] !== undefined && source[key] !== null) {
            form[key] = source[key]
          }
        })
      }
      return form
    }
  }
}
</script>
